# -*- coding = utf-8 -*-
# @Time : 2021/6/30 16:48
# @Author : 龙王赘婿_彪少
# @File : main.py
# @Software: PyCharm

# 模块导入
import sys
from bs4 import BeautifulSoup  # 网页解析
import re  # 正则表达式
import urllib.request, urllib.error  # 指定url，获取网页数据
import xlwt  # 进行excel操作
import sqlite3  # 数据库


def main():
    print("爬虫开始")

    baseurl = "https://movie.douban.com/top250?start="
    # 爬取网页 解析数据
    datalist = getData(baseurl)
    # 保存数据
    savepath = "./file/豆瓣五百强.xls"
    saveData(datalist, savepath)
    dbpath = "./file/movie.db"
    saveDate2DB(datalist, dbpath)

    # askURL(baseurl)
    print("爬虫结束")


# 创建正则表达式对象
findLink = re.compile(r'<a href="(.*?)">')
# re.S 忽略换行符 把.匹配到任意字符 让换行符包含于.中
findImgSrc = re.compile(r'<img.*src="(.*?)"', re.S)
# 篇名
findTitle = re.compile(r'<span class="title">(.*?)</span>')
# 影片评分
findRating = re.compile(r'<span class="rating_num" property="v:average">(.*?)</span>')
# 评价人数
findJudge = re.compile(r'<span>(\d*)人评价</span>')
# 找到概况
findInq = re.compile(r'<span class="inq">(.*)。</span>')
# 找到影片的相关内容
findBd = re.compile(r'<p class="">(.*?)</p>', re.S)


# 爬取网页，解析数据，返回数据
def getData(baseurl):
    datalist = []
    for i in range(0, 10):  # 左闭右开 0~9 共10次
        url = baseurl + str(i * 25)
        html = askURL(url)

        # 逐一解析数据
        soup = BeautifulSoup(html, "html.parser")

        temp = soup.find_all('div', class_="item")
        for item in temp:
            # print(item)
            data = []  # 保存一部电影的所有信息
            item = str(item)
            # print(item)
            # 连接
            link = re.findall(findLink, item)[0]  # 通过正则表达式查找 [0] 表示只取第一个
            data.append(link)
            # 图片
            ImgSrc = re.findall(findImgSrc, item)[0]
            data.append(ImgSrc)
            # 篇名 可能中文外文都有
            Title = re.findall(findTitle, item)
            if (len(Title) == 2):
                ctitle = Title[0]
                data.append(ctitle)
                ctitle = Title[1].replace("/", "")
                data.append(ctitle)
            else:
                data.append(Title[0])
                data.append(' ')

            # 评分
            Rating = re.findall(findRating, item)[0]
            data.append(Rating)
            # 人数
            Judge = re.findall(findJudge, item)[0]
            data.append(Judge)
            # 概况
            inq = re.findall(findInq, item)
            if len(inq) != 0:
                inq[0].replace("。", "")  # 去掉句号
                data.append(inq)
            else:
                data.append(" ")
            # 内容
            Bd = re.findall(findBd, item)[0]
            Bd = re.sub('<br(\s+)?/>(\s+)?', " ", Bd)  # 去br
            Bd = re.sub('\s', " ", Bd)  #
            Bd = re.sub('/', " ", Bd)  # 替换/
            data.append(Bd.strip())  # 去前后空格
            # print(link)
            datalist.append(data)
    # print(datalist)
    return datalist

# 爬取单个网页
# ctrl shift j 合并为一行
def askURL(url):
    head = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWeb; Kit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36"}
    # 告诉豆瓣我们是什么浏览器，豆瓣知道了你是什么浏览器，才会发送给你对应的东西，你才能显示

    # 封装请求对象
    request = urllib.request.Request(url=url, headers=head);
    html = ""
    try:
        resource = urllib.request.urlopen(request)
        html = resource.read().decode("utf-8")
        # print(html)
    except urllib.error.URLError as e:
        if hasattr(e, "code"):
            print(e.code)
        if hasattr(e, "reason"):
            print(e.reason)
    return html

# 保存数据
def saveData(datalist, savepath):
    print("save...")
    book = xlwt.Workbook(encoding="utf-8", style_compression=0)
    # 创建表单
    sheet = book.add_sheet('豆瓣电影Top250', cell_overwrite_ok=True)
    col = ("电影详情链接", "图片链接", "图片中文名", "影片外国名", "评分", "评价数", "概况", "相关信息")
    for i in range(0, 8):
        sheet.write(0, i, col[i])

    for i in range(0, 250):
        print("第%d条" % (i+1))
        data = datalist[i]
        for j in range(0, 8):
            sheet.write(i + 1, j, data[j])

    book.save(savepath)

def saveDate2DB(datalist, dbpath):
    print("创建数据库")
    init_db(dbpath)
    print("开始保存入数据库...")
    conn = sqlite3.connect(dbpath)
    cur = conn.cursor()

    for data in datalist:
        for index in range(len(data)):
            if index == 4 or index == 5:
                continue
            data[index] = '"'+data[index]+'"'
        sql = '''
            insert into movie250(
                info_link, pic_link, cname, ename, score, rated, instroduction,info)
                values(%s)'''%",".join(data)
        cur.execute(sql)
        conn.commit()
    cur.close()
    conn.close()


def init_db(dbpath):
    conn = sqlite3.connect(dbpath)
    cur = conn.cursor()
    sql = '''
        create table if not exists movie250
        (
            id integer primary key autoincrement,
            info_link text,
            pic_link text,
            cname varchar,
            ename varchar,
            score numeric,
            rated numeric,
            instroduction text,
            info text
        );
    '''
    cur.execute(sql)
    conn.commit()
    conn.close()



if __name__ == '__main__':
    main()
    print("end")
